<template>
  <div class="auto-grader-container">
    <div v-if="step < 2" class="step-upload futurism-theme">
      <div class="upload-header">
        <h1>AI 智能试卷分析</h1>
        <p>上传试卷与学生答卷，即刻获取深度学情分析报告</p>
      </div>

      <div class="step-guide">
        <div class="step-item">
          <div class="step-icon-wrapper"><el-icon><DocumentAdd /></el-icon></div>
          <div class="step-info">
            <h4>第一步：上传试卷</h4>
            <p>提供包含标准答案的 .docx 试卷文件</p>
          </div>
        </div>
        <div class="step-separator"></div>
        <div class="step-item">
          <div class="step-icon-wrapper"><el-icon><Edit /></el-icon></div>
           <div class="step-info">
            <h4>第二步：上传答卷</h4>
            <p>提供学生作答的 .docx 或 .txt 文件</p>
          </div>
        </div>
        <div class="step-separator"></div>
        <div class="step-item">
          <div class="step-icon-wrapper"><el-icon><DataLine /></el-icon></div>
           <div class="step-info">
            <h4>第三步：启动分析</h4>
            <p>点击按钮，AI 将立即开始分析与评估</p>
          </div>
        </div>
      </div>

      <div class="upload-pipeline">
        <div class="upload-box-wrapper">
          <el-upload
            ref="examUploadRef"
            class="interactive-upload"
            :auto-upload="false"
            :limit="1"
            :show-file-list="false"
            :class="{ 'is-loaded': files.exam }"
            :on-exceed="(newFiles) => handleExceed(newFiles, examUploadRef)"
            :on-change="(file) => handleFileChange(file, 'exam')"
            accept=".docx"
            drag
          >
            <div v-if="!files.exam" class="upload-prompt">
              <div class="q-icon-crystal">
                <div class="base"></div><div class="shard shard-1"></div><div class="shard shard-2"></div><div class="shard shard-3"></div>
              </div>
              <span class="prompt-text">上传试卷文件</span>
            </div>
            <div v-else class="upload-success">
              <el-icon class="success-icon"><SuccessFilled /></el-icon>
              <div class="file-info">
                <strong class="file-name" :title="files.exam.name">{{ files.exam.name }}</strong>
                <span class="file-size">{{ formatFileSize(files.exam.size) }}</span>
              </div>
              <el-button @click.stop="removeFile('exam')" type="danger" link class="eject-button" :icon="CircleClose" />
            </div>
          </el-upload>
        </div>

        <div class="pipeline-connector"><div class="particle"></div><div class="particle"></div><div class="particle"></div></div>

        <div class="upload-box-wrapper">
          <el-upload
            ref="answersUploadRef"
            class="interactive-upload"
            :auto-upload="false"
            :limit="1"
            :show-file-list="false"
            :class="{ 'is-loaded': files.answers }"
            :on-exceed="(files) => handleExceed(files, answersUploadRef)"
            :on-change="(file) => handleFileChange(file, 'answers')"
            accept=".docx,.txt"
            drag
          >
            <div v-if="!files.answers" class="upload-prompt">
              <div class="q-icon-chip"><div class="chip-body"></div><div class="chip-scanline"></div></div>
              <span class="prompt-text">上传答题卡文件</span>
            </div>
             <div v-else class="upload-success">
              <el-icon class="success-icon"><SuccessFilled /></el-icon>
              <div class="file-info">
                <strong class="file-name" :title="files.answers.name">{{ files.answers.name }}</strong>
                <span class="file-size">{{ formatFileSize(files.answers.size) }}</span>
              </div>
              <el-button @click.stop="removeFile('answers')" type="danger" link class="eject-button" :icon="CircleClose" />
            </div>
          </el-upload>
        </div>
      </div>

      <div class="start-button-container">
        <el-button class="analysis-button" @click="startAnalysis" :disabled="!files.exam || !files.answers">
          <el-icon><MagicStick /></el-icon>
          <span>开始智能分析</span>
        </el-button>
      </div>
    </div>

    <div v-if="step === 2" class="step-loading futurism-theme">
        <div class="ai-core-loader">
            <div class="core-icon">
                <el-icon><DataLine /></el-icon>
            </div>
            <div class="ring ring-1"></div>
            <div class="ring ring-2"></div>
            <div class="ring ring-3"></div>
        </div>
        <h2 class="loading-title">AI 正在分析中...</h2>
        <p class="loading-subtitle">{{ loadingText }}</p>
    </div>

    <div v-if="step === 3 && reportData" class="step-report futurism-theme">
       <el-page-header @back="resetProcess" class="report-page-header">
        <template #content>
          <span class="text-large font-600 mr-3">学情分析报告</span>
        </template>
      </el-page-header>
      
      <el-row :gutter="24" class="report-main-stats">
        <el-col :md="10" :sm="24">
          <el-card class="chart-card">
            <v-chart class="score-gauge-chart" :option="scoreGaugeOption" autoresize />
          </el-card>
        </el-col>
        <el-col :md="14" :sm="24">
          <el-card class="chart-card">
             <v-chart class="radar-chart" :option="radarOption" autoresize />
          </el-card>
        </el-col>
      </el-row>
      
      <el-row :gutter="24">
        <el-col :lg="8" :md="24">
           <el-card class="analysis-card strengths">
             <template #header><div class="analysis-header">👍 优势分析</div></template>
             <ul v-if="reportData.strengths && reportData.strengths.length > 0">
                <li v-for="(item, i) in reportData.strengths" :key="`s-${i}`">{{ item }}</li>
             </ul>
             <el-empty v-else description="暂无明显优势项" :image-size="60" />
           </el-card>
        </el-col>
        <el-col :lg="8" :md="24">
           <el-card class="analysis-card weaknesses">
             <template #header><div class="analysis-header">⚠️ 薄弱环节</div></template>
             <ul v-if="reportData.weaknesses && reportData.weaknesses.length > 0">
                <li v-for="(item, i) in reportData.weaknesses" :key="`w-${i}`">{{ item }}</li>
             </ul>
             <el-empty v-else description="暂无明显薄弱项" :image-size="60" />
           </el-card>
        </el-col>
        <el-col :lg="8" :md="24">
           <el-card class="analysis-card suggestions">
             <template #header><div class="analysis-header">💡 学习建议</div></template>
             <ul v-if="reportData.suggestions && reportData.suggestions.length > 0">
                <li v-for="(item, i) in reportData.suggestions" :key="`g-${i}`">{{ item }}</li>
             </ul>
             <el-empty v-else description="暂无特别建议" :image-size="60" />
           </el-card>
        </el-col>
      </el-row>
    </div>
  </div>
</template>

<script setup>
import { ref, computed } from 'vue';
import { ElMessage, genFileId } from 'element-plus';
import assessmentService from '../../services/assessmentService.js';
import * as echarts from 'echarts';
import { use } from 'echarts/core';
import { GaugeChart, RadarChart } from 'echarts/charts';
import { TitleComponent, TooltipComponent, LegendComponent, GridComponent } from 'echarts/components';
import { CanvasRenderer } from 'echarts/renderers';
import VChart from 'vue-echarts';
import { DocumentAdd, Edit, DataLine, MagicStick, SuccessFilled, CircleClose } from '@element-plus/icons-vue';

use([TitleComponent, TooltipComponent, LegendComponent, GridComponent, CanvasRenderer, GaugeChart, RadarChart]);

const step = ref(1);
const loadingText = ref('正在初始化分析引擎...');
const reportData = ref(null);
const examUploadRef = ref();
const answersUploadRef = ref();
const files = ref({ exam: null, answers: null });

const handleExceed = (newFiles, uploadRef) => {
  if (uploadRef) {
    uploadRef.value.clearFiles();
    const file = newFiles[0];
    file.uid = genFileId();
    uploadRef.value.handleStart(file);
    handleFileChange(file, uploadRef === examUploadRef.value ? 'exam' : 'answers');
  }
};
const handleFileChange = (file, type) => {
  if (file.raw) { files.value[type] = file.raw; } else { files.value[type] = null; }
};
let loadingInterval = null;
const startAnalysis = async () => {
  if (!files.value.exam || !files.value.answers) {
    ElMessage.warning('请先上传所需文件');
    return;
  }
  step.value = 2;
  reportData.value = null;
  const texts = ["正在识别题目结构...", "正在提取知识点...", "正在匹配学生答案...", "正在进行语义分析...", "即将生成报告..."];
  let textIndex = 0;
  loadingText.value = texts[0];
  loadingInterval = setInterval(() => {
    textIndex = (textIndex + 1) % texts.length;
    loadingText.value = texts[textIndex];
  }, 2000);
  try {
    const data = await assessmentService.gradeAndAnalyze(files.value.exam, files.value.answers);
    reportData.value = data;
    clearInterval(loadingInterval);
    ElMessage.success('AI分析完成！');
    step.value = 3;
  } catch (error) {
    clearInterval(loadingInterval);
    ElMessage.error(error.message || '分析失败，请检查文件或联系管理员');
    step.value = 1;
  }
};
const resetProcess = () => {
  step.value = 1;
  files.value = { exam: null, answers: null };
  reportData.value = null;
  examUploadRef.value?.clearFiles();
  answersUploadRef.value?.clearFiles();
};
const removeFile = (type) => {
  files.value[type] = null;
  if (type === 'exam' && examUploadRef.value) { examUploadRef.value.clearFiles(); } 
  else if (type === 'answers' && answersUploadRef.value) { answersUploadRef.value.clearFiles(); }
};
const formatFileSize = (bytes) => {
  if (bytes === 0) return '0 Bytes';
  const k = 1024;
  const i = Math.floor(Math.log(bytes) / Math.log(k));
  return `${parseFloat((bytes / Math.pow(k, i)).toFixed(2))} ${['Bytes', 'KB', 'MB', 'GB', 'TB'][i]}`;
};

// --- ECharts Options with VIBRANT GAME-UI Theme ---
const scoreGaugeOption = computed(() => {
  if (!reportData.value) return {};
  const score = reportData.value?.overallScore || 0;
  return {
    series: [
      // Decorative Outer Ring
      {
        type: 'gauge',
        radius: '100%',
        startAngle: 180, endAngle: 0,
        splitLine: { show: false },
        axisTick: { show: false },
        axisLabel: { show: false },
        pointer: { show: false },
        axisLine: {
          lineStyle: {
            width: 2,
            color: [[1, 'rgba(139, 92, 246, 0.3)']]
          }
        },
        detail: { show: false }
      },
      // Main Score Gauge
      {
        type: 'gauge',
        radius: '85%',
        center: ['50%', '50%'],
        startAngle: 180, endAngle: 0,
        pointer: { show: false },
        progress: {
          show: true,
          roundCap: true,
          width: 20,
          itemStyle: {
            color: new echarts.graphic.LinearGradient(0, 0, 1, 0, [
              { offset: 0, color: '#2dd4bf' }, // Teal
              { offset: 0.5, color: '#4f46e5' }, // Indigo
              { offset: 1, color: '#a855f7' }  // Purple
            ]),
            shadowColor: 'rgba(79, 70, 229, 0.8)',
            shadowBlur: 15,
            shadowOffsetY: 5,
          }
        },
        axisLine: {
          roundCap: true,
          lineStyle: {
            width: 20,
            color: [[1, 'rgba(255, 255, 255, 0.05)']]
          }
        },
        axisTick: { show: false },
        splitLine: { show: false },
        axisLabel: { show: false },
        title: {
          show: true,
          offsetCenter: [0, '20%'],
          color: '#a0aec0',
          fontSize: 16
        },
        detail: {
          valueAnimation: true,
          offsetCenter: [0, '-10%'],
          formatter: (value) => `{value|${value.toFixed(1)}}{unit|分}`,
          rich: {
            value: { fontSize: 48, fontWeight: 'bolder', color: '#FFFFFF', textShadowColor: '#c7d2fe', textShadowBlur: 20 },
            unit: { fontSize: 16, color: '#a0aec0', padding: [0, 0, 10, 4] }
          }
        },
        data: [{ value: score, name: '综合得分' }]
      }
    ]
  };
});

const radarOption = computed(() => {
  const accuracyData = reportData.value?.accuracyByTopic || [];
  return {
    title: { text: '知识点掌握度', left: 'center', top: '5%', textStyle: { color: '#e2e8f0', fontWeight: '600', fontSize: 16 }},
    tooltip: { trigger: 'item', backgroundColor: 'rgba(26, 28, 41, 0.9)', borderColor: '#4a5568', textStyle: { color: '#fff' } },
    radar: {
      indicator: accuracyData.map(item => ({ name: item.topic, max: 100 })),
      shape: 'circle',
      radius: '65%',
      center: ['50%', '55%'],
      axisName: { color: '#c7d2fe', fontSize: 14, textShadowColor: '#c7d2fe', textShadowBlur: 8 },
      splitLine: {
        lineStyle: {
          color: 'rgba(139, 92, 246, 0.3)',
          type: 'dashed'
        }
      },
      splitArea: {
        areaStyle: {
            color: ['rgba(139, 92, 246, 0.05)', 'rgba(139, 92, 246, 0.1)'],
            shadowColor: 'rgba(0, 0, 0, 0.2)',
            shadowBlur: 10
        }
      },
      axisLine: { lineStyle: { color: 'rgba(139, 92, 246, 0.5)' } },
    },
    series: [{
      name: '掌握度',
      type: 'radar',
      data: [{
        value: accuracyData.map(item => (item.accuracy * 100).toFixed(0)),
        name: '学生掌握度',
        symbol: 'circle',
        symbolSize: 10,
        itemStyle: {
            color: '#d8b4fe', // Light purple for points
            borderColor: '#a855f7',
            borderWidth: 2,
            shadowColor: '#a855f7',
            shadowBlur: 10
        },
        lineStyle: {
            color: '#a855f7',
            width: 3,
            shadowColor: '#a855f7',
            shadowBlur: 10,
        },
        areaStyle: {
            color: new echarts.graphic.LinearGradient(0.5, 0, 0.5, 1, [
                { offset: 0, color: 'rgba(168, 85, 247, 0.8)' },
                { offset: 1, color: 'rgba(168, 85, 247, 0.2)' }
            ])
        },
      }]
    }]
  };
});
</script>

<style scoped>
/* ========================================================= */
/* 【Final Corrected】Cohesive Futurism Theme                 */
/* ========================================================= */
.futurism-theme { text-align: center; max-width: 1200px; margin: 20px auto; padding: 40px; border-radius: 20px; background-color: #20212c; background-image: linear-gradient(rgba(139, 92, 246, 0.05) 1px, transparent 1px), linear-gradient(90deg, rgba(139, 92, 246, 0.05) 1px, transparent 1px); background-size: 30px 30px; border: 1px solid rgba(139, 92, 246, 0.2); animation: fadeInUp 0.5s ease-out; }
.upload-header h1 { font-size: 2.2rem; font-weight: 600; color: #fff; }
.upload-header p { font-size: 1rem; color: #a0aec0; margin-top: 8px; margin-bottom: 40px; }

/* Step Guide */
.step-guide { display: flex; justify-content: space-between; align-items: flex-start; gap: 20px; padding: 20px 30px; border-radius: 16px; background: rgba(45, 55, 72, 0.3); border: 1px solid rgba(139, 92, 246, 0.15); margin-bottom: 50px; }
.step-item { display: flex; align-items: center; gap: 15px; text-align: left; flex: 1; }
.step-icon-wrapper { flex-shrink: 0; width: 50px; height: 50px; border-radius: 50%; display: flex; align-items: center; justify-content: center; background: linear-gradient(145deg, #4f46e5, #8b5cf6); color: #fff; font-size: 24px; }
.step-info h4 { margin: 0 0 4px 0; font-size: 1rem; font-weight: 600; color: #edf2f7; }
.step-info p { margin: 0; font-size: 0.85rem; color: #a0aec0; }
.step-separator { flex-shrink: 0; align-self: center; width: 50px; height: 1px; background: linear-gradient(90deg, transparent, rgba(139, 92, 246, 0.4), transparent); }

/* Upload Pipeline & Pods */
.upload-pipeline { display: flex; align-items: center; justify-content: center; gap: 30px; }
.upload-box-wrapper { flex: 1; max-width: 450px; }
.interactive-upload :deep(.el-upload-dragger) { padding: 20px; height: 250px; background-color: rgba(40, 42, 60, 0.5); border: 1px dashed #4a5568; border-radius: 16px; transition: all 0.3s ease; }
.interactive-upload:hover :deep(.el-upload-dragger) { border-color: #8b5cf6; background-color: #4a5568; }
.interactive-upload.is-loaded :deep(.el-upload-dragger) { border-style: solid; border-color: #4f46e5; background: linear-gradient(180deg, #2d3748, #272c44); }
.upload-prompt { display: flex; flex-direction: column; align-items: center; justify-content: center; gap: 15px; color: #a0aec0; }
.prompt-text { font-weight: 500; font-size: 1.1rem; color: #e2e8f0; }

/* Q-Style Icons & Success State */
@keyframes pulse { 0%, 100% { transform: scale(1); opacity: 0.8; } 50% { transform: scale(1.05); opacity: 1; } }
.q-icon-crystal { width: 80px; height: 80px; position: relative; animation: pulse 3s ease-in-out infinite; margin-bottom: 10px; }
.q-icon-crystal .base { width: 50%; height: 50%; background: linear-gradient(135deg, #a78bfa, #4f46e5); position: absolute; top: 25%; left: 25%; transform: rotate(45deg); }
.q-icon-crystal .shard { position: absolute; width: 0; height: 0; border-style: solid; border-color: transparent transparent #c7d2fe; }
.shard-1 { top: 0; left: 25%; border-width: 0 15px 20px 15px; }
.shard-2 { right: 0; top: 25%; border-width: 15px 20px 15px 0; border-color: transparent #c7d2fe transparent transparent; }
.shard-3 { bottom: 0; left: 25%; border-width: 20px 15px 0 15px; border-color: #c7d2fe transparent transparent transparent; }

@keyframes scan { 0% { top: -100%; } 50%, 100% { top: 150%; } }
.q-icon-chip { width: 70px; height: 85px; position: relative; margin-bottom: 10px; }
.q-icon-chip .chip-body { width: 100%; height: 100%; background: #373a51; border: 2px solid #6366f1; border-radius: 8px; position: relative; }
.q-icon-chip .chip-body::before { content: ''; position: absolute; top: 8px; left: 8px; right: 8px; bottom: 18px; background: #1a1c29; border-radius: 4px; }
.q-icon-chip .chip-body::after { content: ''; position: absolute; bottom: 8px; left: 8px; right: 8px; height: 4px; background: #6366f1; }
.chip-scanline { position: absolute; top: 0; left: 0; right: 0; height: 100%; overflow: hidden; border-radius: 8px; }
.chip-scanline::before { content: ''; position: absolute; left: 0; right: 0; height: 2px; background: #a78bfa; box-shadow: 0 0 10px #a78bfa; animation: scan 2.5s linear infinite; }

.upload-success { display: flex; flex-direction: column; align-items: center; justify-content: center; gap: 20px; position: relative; width: 100%; height: 100%; }
.success-icon { font-size: 50px; color: #34d399; }
.file-info { text-align: center; max-width: 90%; }
.file-name { display: block; font-weight: 600; font-size: 1rem; color: #e2e8f0; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
.file-size { color: #a0aec0; font-size: 0.9rem; }
.eject-button { position: absolute; top: 10px; right: 10px; font-size: 20px; color: #718096; }
.eject-button:hover { color: #fca5a5; }

/* Connector & Button */
@keyframes flow { to { transform: translateX(35px); opacity: 0; } }
.pipeline-connector { width: 70px; height: 2px; background: rgba(139, 92, 246, 0.3); align-self: center; position: relative; }
.particle { position: absolute; width: 6px; height: 6px; background: #c7d2fe; border-radius: 50%; left: 0; top: -2px; animation: flow 1.5s linear infinite; }
.particle:nth-child(2) { animation-delay: 0.5s; }
.particle:nth-child(3) { animation-delay: 1s; }

.start-button-container { margin-top: 50px; }
.analysis-button { border: none; font-size: 1.1rem; font-weight: 600; color: #fff; padding: 16px 40px; height: auto; border-radius: 30px; background: linear-gradient(90deg, #4f46e5, #8b5cf6); box-shadow: 0 5px 15px rgba(139, 92, 246, 0.4); transition: all 0.3s ease; position: relative; overflow: hidden; }
.analysis-button .el-icon { margin-right: 10px; }
.analysis-button:hover { transform: translateY(-3px); box-shadow: 0 8px 25px rgba(139, 92, 246, 0.5); }
.analysis-button:disabled { background: #373a51; box-shadow: none; color: #8c8fb0; cursor: not-allowed; }

/* --- Loading Screen Styles --- */
.step-loading { display: flex; flex-direction: column; align-items: center; justify-content: center; height: 70vh; gap: 30px; }
@keyframes rotate { to { transform: rotate(360deg); } }
@keyframes pulse-core { 50% { transform: scale(1.1); filter: brightness(1.2); } }
.ai-core-loader { width: 150px; height: 150px; position: relative; }
.core-icon { width: 100%; height: 100%; display: flex; align-items: center; justify-content: center; font-size: 50px; color: #c7d2fe; z-index: 2; animation: pulse-core 2s ease-in-out infinite; }
.ring { position: absolute; inset: 0; border-radius: 50%; border: 3px solid transparent; border-top-color: #8b5cf6; animation: rotate 2s linear infinite; }
.ring-2 { animation-direction: reverse; animation-duration: 2.5s; border-top-color: #4f46e5; }
.ring-3 { animation-duration: 3s; border-top-color: #a78bfa; transform: scale(0.8); }
.loading-title { font-size: 1.5rem; color: #fff; }
.loading-subtitle { font-size: 1rem; color: #a0aec0; }

/* --- Report Screen Styles (Vibrancy & Clarity FINAL) --- */
.step-report { padding: 20px; }
.step-report :deep(.el-page-header__header) {
  height: 48px;
}
.step-report :deep(.el-page-header__back .el-icon) {
  color: #c7d2fe;
  font-size: 18px;
}
.step-report :deep(.el-page-header__content) {
  color: #FFFFFF !important;
  font-size: 18px;
  font-weight: 600;
  text-shadow: 0 0 5px rgba(255, 255, 255, 0.5);
}

.report-main-stats { margin-bottom: 24px; }
.step-report .el-col { margin-bottom: 24px; }

.step-report .el-card {
  background-color: #2d3748 !important;
  border: 1px solid #4a5568 !important;
  color: #e2e8f0 !important;
  --el-card-padding: 0;
  backdrop-filter: none !important;
  -webkit-backdrop-filter: none !important;
  transition: all 0.3s ease;
  height: 100%;
}
.step-report .el-card:hover {
  border-color: #8b5cf6;
  transform: translateY(-5px);
  box-shadow: 0 10px 20px rgba(0,0,0,0.3);
}

.step-report .chart-card { height: 350px; }
.step-report .chart-card :deep(.el-card__body) { padding: 15px; height: 100%; box-sizing: border-box; }
.score-gauge-chart, .radar-chart { height: 100%; width: 100%; }

.step-report .analysis-card { display: flex; flex-direction: column; }
.step-report .analysis-card :deep(.el-card__header) {
  color: #fff;
  font-weight: 600;
  border-bottom: 1px solid #4a5568;
}
.step-report .analysis-card :deep(.el-card__body) { padding: 20px; flex-grow: 1; }

.analysis-header {
  font-size: 1rem;
  font-weight: 600;
  display: flex;
  align-items: center;
  gap: 12px;
}
/* Enhanced Icon Styles */
.analysis-header span:first-child {
  width: 32px;
  height: 32px;
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 16px;
  color: #fff;
}
.strengths span:first-child { background-color: #10b981; box-shadow: 0 0 10px #10b981; }
.weaknesses span:first-child { background-color: #f59e0b; box-shadow: 0 0 10px #f59e0b; }
.suggestions span:first-child { background-color: #3b82f6; box-shadow: 0 0 10px #3b82f6; }

.step-report .analysis-card ul { list-style: none; padding: 0; margin: 0; }
.step-report .analysis-card li {
  padding: 12px 5px;
  border-bottom: 1px solid #4a5568;
  color: #e2e8f0;
  line-height: 1.6;
}
.step-report .analysis-card li:last-child { border-bottom: none; }
.step-report .el-empty { --el-empty-text-color: #718096; --el-empty-color: #4a5568; }
</style>